import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: () => import('@/views/login.vue')
  },
  {
    path: '/',
    redirect: '/dashboard/welcome'
  },
  {
    path: '/dashboard/welcome',
    component: () => import('@/views/home.vue'),
    children: [
      {
        path: '/',
        component: () => import('@/views/Welcome/Index.vue')
      },
      {
        path: '/dashboard/user/index',
        component: () => import('@/views/User/Index.vue')
      },
      {
        path: '/dashboard/user/add',
        component: () => import('@/views/User/Add.vue')
      },
      {
        path: '/dashboard/user/mod',
        component: () => import('@/views/User/Mod.vue')
      }
    ]
  }
]

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err)
}

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 前置守卫
router.beforeEach((to, from, next) => {
  // 判断目标是否为登录页 - 去登录 - 放行
  if (to.path === '/login') {
    next()
  } else {
    // 判断是否已经登录
    if (store.state.token) {
      // 存在 - 放行
      next()
    } else {
      // 不存在 - 去登录
      router.push('/login')
    }
  }
})

// 后置守卫 - 只能访问规定好的路由
router.afterEach((to, from) => {
  var index = store.state.auth.findIndex((item) => item === to.path)
  if (index < 0) {
    // 如果没有找到该权限 - 返回到首页（非登录页）
    router.push('/')
  }
})

export default router
